package com.pimee.service.admin.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.pimee.common.exception.BusinessException;
import com.pimee.common.util.DateUtil;
import com.pimee.common.util.StringUtils;
import com.pimee.mapper.ext.ExtSysMenuMapper;
import com.pimee.model.SysMenu;
import com.pimee.model.SysUser;
import com.pimee.model.vo.SysMenuVo;
import com.pimee.model.web.Ztree;
import com.pimee.service.BaseService;
import com.pimee.service.admin.ISysMenuService;
import com.pimee.service.admin.ISysUserService;
import com.pimee.service.util.TreeUtils;

import tk.mybatis.mapper.entity.Example;

@Service
public class SysMenuService extends BaseService<SysMenu> implements ISysMenuService {

	@Autowired
	private ExtSysMenuMapper extSysMenuMapper;
	@Autowired
	private ISysUserService sysUserService;
	
	/**
     * 根据用户查询菜单
     * 
     * @param user 用户信息
     * @return 菜单列表
     */
    @Override
    public List<SysMenuVo> selectMenusByUser(SysUser user) {
        List<SysMenuVo> menus = new LinkedList<>();
        // 超级管理员显示所有菜单信息
        if (sysUserService.isAdmin(user.getUserId())) {
            menus = extSysMenuMapper.selectMenuNormalAll();
        } else {
            menus = extSysMenuMapper.selectMenusByUserId(user.getUserId());
        }
        return TreeUtils.getChildPerms(menus, 0);
    }
    /**
     * 根据用户ID查询权限
     * 
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectPermsByUserId(Long userId) {
        List<String> perms = extSysMenuMapper.selectPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms){
            if (StringUtils.isNotEmpty(perm)){
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }
    
    /**
     * 查询菜单集合
     * 
     * @return 所有菜单信息
     */
    @Override
    public List<SysMenuVo> listMenu(Map<String, Object> params)  {
    	Long userId = (Long) params.get("userId");
    	List<SysMenuVo> menuList = null;
    	if (sysUserService.isAdmin(userId)) {
    		menuList = extSysMenuMapper.selectMenuList(params);
        } else {
        	menuList = extSysMenuMapper.selectMenuListByUserId(params);
        }
        return menuList;
    }
	@Override
	public Object insertMenu(SysMenu param) {
		Example example = new Example(SysMenu.class);
    	example.createCriteria().andEqualTo("menuName", param.getMenuName());
        int count = this.countByExample(example);
        if(count > 0) {
        	throw new BusinessException("菜单已经存在！");
        }
        Date now = DateUtil.now();
        param.setCreateTime(now);
        param.setUpdateTime(now);
		return this.saveNotNull(param);
	}
	@Override
	public Object deleteMenuById(Long menuId) {
		String msg = "存在子菜单,不允许删除";
		Example example = new Example(SysMenu.class);
    	example.createCriteria().andEqualTo("parentId", menuId);
    	int count = this.countByExample(example);
    	if(count > 0) {
        	throw new BusinessException(msg);
        }
    	
    	return this.deleteByKey(menuId);
	}
	@Override
	public void updateMenu(SysMenu menu) {
		menu.setUpdateTime(DateUtil.now());
		this.updateNotNull(menu);
	}
    
	/**
     * 查询所有菜单
     * 
     * @return 菜单列表
     */
    @Override
    public List<Ztree> menuTreeData(Long userId) {
    	Map<String, Object> params = Maps.newHashMap();
    	params.put("userId", userId);
        List<SysMenuVo> menuList = listMenu(params);
        List<Ztree> ztrees = initZtree(menuList);
        return ztrees;
    }
    
    /**
     * 对象转菜单树
     * 
     * @param menuList 菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysMenuVo> menuList) {
        return initZtree(menuList, null, false);
    }

    /**
     * 对象转菜单树
     * 
     * @param menuList 菜单列表
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag 是否需要显示权限标识
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysMenuVo> menuList, List<String> roleMenuList, boolean permsFlag) {
        List<Ztree> ztrees = new ArrayList<>();
        boolean isCheck = StringUtils.isNotNull(roleMenuList);
        for (SysMenuVo menu : menuList) {
            Ztree ztree = new Ztree();
            ztree.setId(menu.getMenuId());
            ztree.setpId(menu.getParentId());
            ztree.setName(transMenuName(menu, permsFlag));
            ztree.setTitle(menu.getMenuName());
            if (isCheck) {
                ztree.setChecked(roleMenuList.contains(menu.getMenuId() + menu.getPerms()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }

    public String transMenuName(SysMenuVo menu, boolean permsFlag) {
        StringBuffer sb = new StringBuffer();
        sb.append(menu.getMenuName());
        if (permsFlag){
            sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menu.getPerms() + "</font>");
        }
        return sb.toString();
    }
    
	@Override
	public List<Ztree> roleMenuTreeData(Long userId, Long roleId) {
		Map<String, Object> params = Maps.newHashMap();
    	params.put("userId", userId);
        List<SysMenuVo> menuList = listMenu(params);
		List<Ztree> ztrees = new ArrayList<Ztree>();
        if (StringUtils.isNotNull(roleId)) {
            List<String> roleMenuList = extSysMenuMapper.selectMenuTree(roleId);
            ztrees = initZtree(menuList, roleMenuList, true);
        }
        else {
            ztrees = initZtree(menuList, null, true);
        }
        return ztrees;
	}
    
}
